package com.bookstore.back.service.impl;

import com.bookstore.back.entity.User;
import com.bookstore.back.mapper.UserMapper;
import com.bookstore.back.service.UserProfileService;
import com.bookstore.back.util.UserContextUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

/**
 * 用户个人资料服务实现类
 * 
 * @author 程序猿_Ti
 * @since 2025-07-22
 */
@Slf4j
@Service
public class UserProfileServiceImpl implements UserProfileService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private UserContextUtil userContextUtil;

    @Override
    public Map<String, Object> getUserProfile() {
        try {
            // 获取当前登录用户ID
            Long currentUserId = userContextUtil.getCurrentUserId();
            if (currentUserId == null) {
                throw new RuntimeException("未登录或登录已过期");
            }

            // 验证当前用户是否为普通用户
            if (!userContextUtil.isCurrentUserRegular()) {
                throw new RuntimeException("权限不足，只有普通用户可以访问");
            }

            User user = userMapper.selectById(currentUserId);
            if (user == null) {
                throw new RuntimeException("用户信息不存在");
            }

            // 构建返回的用户资料信息（不包含敏感信息）
            Map<String, Object> profile = new HashMap<>();
            profile.put("id", user.getId());
            profile.put("username", user.getUsername());
            profile.put("email", user.getEmail());
            profile.put("phone", user.getPhone());
            profile.put("realName", user.getRealName());
            profile.put("avatar", user.getAvatar());
            profile.put("gender", user.getGender());
            profile.put("birthDate", user.getBirthDate());
            profile.put("balance", user.getBalance());
            profile.put("status", user.getStatus());
            profile.put("createTime", user.getCreateTime());
            profile.put("updateTime", user.getUpdateTime());

            return profile;
        } catch (Exception e) {
            log.error("获取用户个人资料失败：{}", e.getMessage());
            throw new RuntimeException("获取个人资料失败：" + e.getMessage());
        }
    }

    @Override
    public boolean updateUserProfile(Map<String, Object> profileData) {
        try {
            // 获取当前登录用户ID
            Long currentUserId = userContextUtil.getCurrentUserId();
            if (currentUserId == null) {
                throw new RuntimeException("未登录或登录已过期");
            }

            // 验证当前用户是否为普通用户
            if (!userContextUtil.isCurrentUserRegular()) {
                throw new RuntimeException("权限不足，只有普通用户可以访问");
            }

            User user = userMapper.selectById(currentUserId);
            if (user == null) {
                throw new RuntimeException("用户信息不存在");
            }

            // 更新个人资料信息
            if (profileData.containsKey("username")) {
                String username = (String) profileData.get("username");
                if (username != null && !username.trim().isEmpty()) {
                    // 检查用户名是否已被其他用户使用
                    if (!username.equals(user.getUsername())) {
                        int count = userMapper.checkUsernameExists(username);
                        if (count > 0) {
                            throw new RuntimeException("用户名已存在");
                        }
                    }
                    user.setUsername(username);
                }
            }
            if (profileData.containsKey("email")) {
                String email = (String) profileData.get("email");
                if (email != null && !email.trim().isEmpty()) {
                    // 检查邮箱是否已被其他用户使用
                    if (!email.equals(user.getEmail())) {
                        int count = userMapper.checkEmailExists(email);
                        if (count > 0) {
                            throw new RuntimeException("邮箱已存在");
                        }
                    }
                    user.setEmail(email);
                }
            }
            if (profileData.containsKey("phone")) {
                String phone = (String) profileData.get("phone");
                if (phone != null && !phone.trim().isEmpty()) {
                    // 检查手机号是否已被其他用户使用
                    if (!phone.equals(user.getPhone())) {
                        int count = userMapper.checkPhoneExists(phone);
                        if (count > 0) {
                            throw new RuntimeException("手机号已存在");
                        }
                    }
                    user.setPhone(phone);
                }
            }
            if (profileData.containsKey("realName")) {
                user.setRealName((String) profileData.get("realName"));
            }
            if (profileData.containsKey("gender")) {
                user.setGender((Integer) profileData.get("gender"));
            }
            if (profileData.containsKey("birthDate")) {
                String birthDateStr = (String) profileData.get("birthDate");
                if (birthDateStr != null && !birthDateStr.isEmpty()) {
                    user.setBirthDate(LocalDate.parse(birthDateStr));
                }
            }

            user.setUpdateTime(LocalDateTime.now());
            int result = userMapper.updateById(user);
            return result > 0;
        } catch (Exception e) {
            log.error("更新用户个人资料失败：{}", e.getMessage());
            throw new RuntimeException("更新个人资料失败：" + e.getMessage());
        }
    }

    @Override
    public boolean changeUserPassword(String currentPassword, String newPassword) {
        try {
            // 获取当前登录用户ID
            Long currentUserId = userContextUtil.getCurrentUserId();
            if (currentUserId == null) {
                throw new RuntimeException("未登录或登录已过期");
            }

            // 验证当前用户是否为普通用户
            if (!userContextUtil.isCurrentUserRegular()) {
                throw new RuntimeException("权限不足，只有普通用户可以访问");
            }

            User user = userMapper.selectById(currentUserId);
            if (user == null) {
                throw new RuntimeException("用户信息不存在");
            }

            // 验证当前密码（明文比较，与登录逻辑保持一致）
            if (!currentPassword.equals(user.getPassword())) {
                throw new RuntimeException("当前密码不正确");
            }

            // 验证新密码不能与当前密码相同
            if (currentPassword.equals(newPassword)) {
                throw new RuntimeException("新密码不能与当前密码相同");
            }

            // 更新密码（明文存储，与现有数据保持一致）
            user.setPassword(newPassword);
            user.setUpdateTime(LocalDateTime.now());

            int result = userMapper.updateById(user);
            if (result <= 0) {
                throw new RuntimeException("密码更新失败");
            }
            return true;
        } catch (RuntimeException e) {
            throw e;
        } catch (Exception e) {
            log.error("修改用户密码失败：{}", e.getMessage());
            throw new RuntimeException("修改密码失败：" + e.getMessage());
        }
    }

    @Override
    public boolean updateUserAvatar(String avatarUrl) {
        try {
            // 获取当前登录用户ID
            Long currentUserId = userContextUtil.getCurrentUserId();
            if (currentUserId == null) {
                throw new RuntimeException("未登录或登录已过期");
            }

            // 验证当前用户是否为普通用户
            if (!userContextUtil.isCurrentUserRegular()) {
                throw new RuntimeException("权限不足，只有普通用户可以访问");
            }

            User user = new User();
            user.setId(currentUserId);
            user.setAvatar(avatarUrl);
            user.setUpdateTime(LocalDateTime.now());

            int result = userMapper.updateById(user);
            return result > 0;
        } catch (Exception e) {
            log.error("更新用户头像失败：{}", e.getMessage());
            throw new RuntimeException("更新头像失败：" + e.getMessage());
        }
    }
}
